package app.hzvmap.com.rangecontrol;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.tencent.bugly.Bugly;
//import com.tencent.bugly.Bugly;

import org.xutils.x;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import app.hzvmap.com.rangecontrol.model.Position;
import app.hzvmap.com.rangecontrol.utils.AppSetting;
import app.hzvmap.com.rangecontrol.utils.DbHelper;
import app.hzvmap.com.rangecontrol.utils.netty.LogPushUdpClient;
import app.hzvmap.com.rangecontrol.utils.netty.LogPushUdpClientHandler;

import static android.content.ContentValues.TAG;

public class App extends Application {
    private static App instance;

    private Activity topActivity;

    private int intLevel;

    private int intScale;

    public static Map<String, List<Position>> POSITIONTEMP = new HashMap<>();

    public AMapLocationClient locationClient = null;

    public static Position POSITION;

    public static SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyyMMddHHmmss");


    public static InetSocketAddress REMOTEADD = new InetSocketAddress("218.108.42.76", 8081);


    Handler handler = new Handler() {
        public void handleMessage(android.os.Message paramMessage) {
            if (paramMessage.what == 1) {
                try {
                    Message message = (Message) paramMessage.obj;
                    NotificationManager notifyManager = (NotificationManager) App.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(App.getInstance())
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND);

                    notifyManager.notify(0, builder.build());
                } catch (Exception e) {
                    Log.d(TAG, "show message Error" + e.getMessage()); //$NON-NLS-1$
                }
            }
        }
    };

    //创建BroadcastReceiver
    private BroadcastReceiver mBatInfoReveiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //如果捕捉到的Action是ACTION_BATTERY_CHANGED则运行onBatteryInforECEIVER()
            if (intent.ACTION_BATTERY_CHANGED.equals(action)) {
                //获得当前电量
                intLevel = intent.getIntExtra("level", 0);
                //获得手机总电量
                intScale = intent.getIntExtra("scale", 100);
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            // This process is dedicated to LeakCanary for heap analysis.
//            // You should not init your app in this process.
//            return;
//        }
//        LeakCanary.install(this);

        initChannel();
        x.Ext.init(this);
        instance = this;

//        CustomActivityOnCrash.install(this);

        SendTempContent sendTempContent = new SendTempContent();
        sendTempContent.start();

        try {
            LogPushUdpClient.getInstance().start();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 注册一个BroadcastReceiver，作为访问电池计量之用
        registerReceiver(mBatInfoReveiver, new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED));

        Bugly.init(getApplicationContext(), "71b77961e9", true);

    }

    public Activity getTopActivity() {
        return topActivity;
    }

    public void setTopActivity(Activity topActivity) {
        this.topActivity = topActivity;
    }

    public static App getInstance() {
        return instance;
    }

    public void setLocationListener(AMapLocationListener listener) {
        if (locationClient != null) {
            locationClient.setLocationListener(listener);
        }
    }

    public void unRegisterLocationListener(AMapLocationListener listener) {
        if (locationClient != null) {
            locationClient.unRegisterLocationListener(listener);
        }
    }

    public void startLocation() {
        if (locationClient != null && !locationClient.isStarted()) {
            locationClient.startLocation();
        }
    }

    public void stopLocation() {
        if (locationClient != null && locationClient.isStarted()) {
            locationClient.stopLocation();
            if (locationClient != null) {
                locationClient.onDestroy();
                locationClient = null;
            }
        }
    }

    class SendTempContent extends Thread {

        @Override
        public void run() {

            while (true) {

                try {
                    List<Position> positions = DbHelper.getDb().selector(Position.class).limit(10).offset(0).findAll();
                    if (positions != null && positions.size() > 0) {
                        String gps = "";
                        for (int i = 0; i < positions.size(); i++) {
                            Position p = positions.get(i);
                            if (i > 0) {
                                gps += "#";
                            }
                            gps += String.format("%s|%s|%.6f|%.6f|%d|%d|%d", p.getGuid(), p.getTime().replace("-", "").replace(" ", "").replace(":", ""), p.getLongitude(), p.getLatitude(), (int) p.getAltitude(), (int) p.getSpeed(), (int) p.getBearing());
                        }
                        UUID uuid = UUID.randomUUID();
                        POSITIONTEMP.put(uuid.toString().replace("-", ""), positions);
                        LogPushUdpClientHandler.senderInternal(String.format("**T|%s|%s>%s", uuid.toString().replace("-", ""), AppSetting.getAppSetting(App.getInstance()).GUID.get(), gps), REMOTEADD, positions);
                        Thread.sleep(10000);
                    } else {
                        Thread.sleep(60000);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }


        SendTempContent() {
        }
    }

    public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "app.hzvmap.com.rangecontrol.service";
    public static final String NOTIFICATION_CHANNEL_ID_TASK = "com.mypackage.download_info";

    public void initChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
        }
    }
}
